import tensorflow as tf
from tensorflow.keras import datasets, layers, optimizers, Sequential, metrics
import tensorflow.keras as keras


class Cifar10Dense(layers.Layer):
    def __init__(self, input_dim, output_dim):
        super(Cifar10Dense, self).__init__()

        self.kernel = self.add_weight('w', [input_dim, output_dim])
        self.bias = self.add_weight('b', [output_dim])

    def call(self, inputs, training=None):
        x = inputs @ self.kernel + self.bias
        return x


class Cifar10Network(keras.Model):
    def __init__(self):
        super(Cifar10Network, self).__init__()

        self.fc1 = Cifar10Dense(32 * 32 * 3, 512)
        self.fc2 = Cifar10Dense(512, 256)
        self.fc3 = Cifar10Dense(256, 64)
        self.fc4 = Cifar10Dense(64, 32)
        self.fc5 = Cifar10Dense(32, 10)

    def call(self, inputs, training=None):
        """
        :param inputs: [b, 32, 32, 3]
        :param training:
        :param mask:
        :return:
        """
        x = tf.reshape(inputs, [-1, 32 * 32 * 3])

        x = self.fc1(x)
        x = tf.nn.relu(x)

        x = self.fc2(x)
        x = tf.nn.relu(x)

        x = self.fc3(x)
        x = tf.nn.relu(x)

        x = self.fc4(x)
        x = tf.nn.relu(x)

        x = self.fc5(x)

        return x


def preprocess(x, y):
    x = 2 * tf.cast(x, dtype=tf.float32) / 255. - 1
    y = tf.cast(y, dtype=tf.int32)
    y = tf.one_hot(y, depth=10)

    return x, y


batch_size = 128

(x_train, y_train), (x_test, y_test) = datasets.cifar10.load_data()
print('dataset value: ', x_train.shape, y_train.shape, x_train.min(), x_train.max())

print(y_train)
print(y_test)
# [50k, 1] ==> [50k]
y_train = tf.squeeze(y_train)
y_test = tf.squeeze(y_test)
print(y_train)
print(y_test)

# # one hot coding
# y_train = tf.one_hot(y_train, depth=10)
# y_test = tf.one_hot(y_test, depth=10)

print('dataset(train): ', x_train.shape, y_train.shape, x_train.min(), x_train.max())
print('dataset(test) : ', x_test.shape, y_test.shape, x_test.min(), x_test.max())

train_ds = tf.data.Dataset.from_tensor_slices((x_train, y_train))
train_ds = train_ds.map(preprocess).shuffle(10000).batch(batch_size).repeat()

test_ds = tf.data.Dataset.from_tensor_slices((x_test, y_test))
test_ds = test_ds.map(preprocess).batch(batch_size)

# sample = next(iter(train_ds))
# print('train dataset batch: ', sample[0].shape, sample[1].shape)

network = Cifar10Network()
network.compile(optimizer=optimizers.Adam(lr=1e-3),
                loss=tf.losses.CategoricalCrossentropy(from_logits=True),
                metrics=['accuracy']
                )

network.fit(train_ds,
            epochs=20,
            validation_data=test_ds,
            validation_freq=5,
            validation_steps=5,
            steps_per_epoch=x_train.shape[0] / batch_size + 1)

network.evaluate(test_ds)
